﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ValidateImageBase.cs
// 功能描述：TEC.Public.Component.ValidateCode
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using TEC.Public.Common;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace TEC.Web.Component.ValidateCode
{
    /// <summary>
    ///图片验证码基类（已实现基本功能）
    /// </summary>
    public abstract class ValidateImageBase : IValidateCode
    {
        System.Drawing.Imaging.ImageFormat imageformat = System.Drawing.Imaging.ImageFormat.Png;
        /// <summary>
        /// 图片验证码图片格式 默认Png
        /// </summary>
        public ImageFormat CodeImageFormat
        {
            get
            {
                return imageformat;
            }

            set
            {
                imageformat = value;
            }
        }

        protected ValidateImageBase()
        {
            //避免在程序集外面实例化或继承
        }

        #region 内部调用函数
        /// <summary>
        /// 生成验证码值
        /// </summary>
        /// <returns></returns>
        protected virtual string CreateCheckCode()
        {
            int number;
            string checkCode = String.Empty;
            Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                number = random.Next(65, 90);
                checkCode += (char)number;
            }
            return checkCode;
        }
        /// <summary>
        /// 验证码的存储 (如果重新这个，相应应该重新 GetTempSavedCode、RemoveTempSaveCode 方法)
        /// </summary>
        /// <param name="code"></param>
        /// <param name="id">存储标识</param>
        protected abstract void SaveTempCode(string code, object id);
        /// <summary>
        /// 获取存储的验证码的值(如果重新这个，相应应该重新 SaveTempCode、RemoveTempSaveCode 方法)
        /// </summary>
        /// <param name="id">存储标识</param>
        /// <returns></returns>
        protected abstract object GetTempSavedCode(object id);

        /// <summary>
        /// 失效不需要的验证码(如果重新这个，相应应该重新 SaveTempCode、SaveTempCode 方法)
        /// </summary>
        /// <param name="id">存储标识</param>
        protected abstract void RemoveTempSaveCode(object id);
        /// <summary>
        /// 生成验证码的算法
        /// </summary>
        /// <param name="checkCode"></param>
        /// <returns></returns>
        protected virtual Bitmap CreateBitImage(string checkCode)
        {
            System.Drawing.Bitmap image;
            if (string.IsNullOrWhiteSpace(checkCode))
                return new System.Drawing.Bitmap(1, 1);
            else
            {
                int fontsize = 23;

                image = new System.Drawing.Bitmap(checkCode.Length * fontsize, 35);

                Graphics g = Graphics.FromImage(image);
                int scharW = 18;
                int scharH = 30;
                try
                {

                    Random random = new Random();

                    //g.Clear(Color.AliceBlue);
                    //Color c1 = Color.FromArgb(21, 101, 160);
                    // Color c1 = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
                    Color[][] bgfcolor = new Color[][] { /*new Color[] { Color.FromArgb(247, 254, 236), Color.FromArgb(226, 51, 8) },*/ new Color[] { Color.FromArgb(235, 244, 253), Color.FromArgb(28, 108, 159) }, new Color[] { Color.FromArgb(245, 250, 244), Color.FromArgb(59, 120, 0) } };
                    int index = random.Next(0, bgfcolor.Length);
                    Color c1 = bgfcolor[index][0];
                    Color cbg = bgfcolor[index][1];
                    g.Clear(cbg);
                    ////画图片的前景噪音点
                    //for (int i = 0; i < 100; i++)
                    //{
                    //    int x1 = random.Next(image.Width);
                    //    int y1 = random.Next(image.Height);

                    //    image.SetPixel(x1, y1, Color.FromArgb(random.Next()));
                    //}
                    ////画图片的背景噪音线
                    //for (int i = 0; i < 10; i++)
                    //{
                    //    int x1 = random.Next(image.Width);
                    //    int x2 = random.Next(image.Width);
                    //    int y1 = random.Next(image.Height);
                    //    int y2 = random.Next(image.Height);

                    //    g.DrawLine(new Pen(Color.FromArgb(100, 235, 244, 253)), x1, y1, x2, y2);
                    //}
                    //string[] fonts = { "Times New Roman", "Arial", "Verdana", "Rosewood Std" "Segoe Print",};
                    string[] fonts = {/* "Arial", */"Times New Roman"/*, "Algerian"*/ };
                    //Color fcolor = Color.FromArgb(255 - c1.R, 255 - c1.G, 255 - c1.B);
                    Brush brush = new System.Drawing.SolidBrush(Color.FromArgb(125, 235, 244, 253));

                    // Create pen.
                    //Pen blackPen = new Pen(Color.Black, 3);
                    for (int i = 0; i < checkCode.Length; i++)
                    {
                        System.Drawing.Bitmap charBitmap = new Bitmap(scharH * 2, scharH * 2);
                        Graphics charG = Graphics.FromImage(charBitmap);
                        //charG.Clear(c1);
                        //charG.DrawRectangle(new Pen(Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255))), 0, 0, 
                        //    charBitmap.Width-1, charBitmap.Height-1);
                        charG.TranslateTransform(scharW / 2, scharH / 2);
                        int rsize = fontsize;
                        // Matrix matrix = new Matrix();
                        float angle = random.Next(-30, 30);
                        PointF pf = new PointF(0, 0);
                        // matrix.Rotate(angle);
                        //matrix.RotateAt(angle, pf);
                        //charG.DrawEllipse(new Pen(Color.Red), new RectangleF(pf, new SizeF(3, 3)));
                        //charG.Transform = matrix;
                        charG.RotateTransform(angle);
                        //charG.FillRectangle(new SolidBrush(cbg), new RectangleF(-scharW / 2, -scharH / 2, scharW, scharH));
                        Font font = new System.Drawing.Font(fonts[random.Next(0, fonts.Length)], rsize, (System.Drawing.FontStyle.Bold));

                        Brush bbrush = new System.Drawing.SolidBrush(c1);
                        pf = new PointF(-scharW / 2, -scharH / 2);
                        charG.DrawString(checkCode[i].ToString(), font, bbrush, pf);
                        //matrix.Invert();
                        g.DrawImage(charBitmap, 3 + scharW * i, 0);
                    }
                    int c = random.Next(3, 6);
                    Point[] bezierPoints = new Point[c * 3 + 1];
                    int w = image.Width / c;
                    int x = 0;
                    for (int i = 0; i < bezierPoints.Length - 1; i++)
                    {
                        int y = random.Next(image.Height / 4, image.Height * 3 / 4);
                        bezierPoints[i] = new Point(i * w + x, y);
                    }
                    bezierPoints[bezierPoints.Length - 1] = new Point(image.Width, random.Next(0, image.Height));

                    g.DrawCurve(new Pen(brush, 20F), bezierPoints);
                    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                }
                catch (Exception ex)
                {
                    throw new Exception("验证码生成出错", ex);
                }
                finally
                {

                    g.Dispose();
                    // image.Dispose();
                }
            }
            return image;

            #region old
            //if (string.IsNullOrWhiteSpace(checkCode))
            //    return null;
            //MemoryStream ms = new System.IO.MemoryStream();
            //System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            //Graphics g = Graphics.FromImage(image);
            //try
            //{
            //    //生成随机生成器
            //    Random random = new Random();

            //    //清空图片背景色
            //    g.Clear(Color.White);

            //    //画图片的背景噪音线
            //    for (int i = 0; i < 2; i++)
            //    {
            //        int x1 = random.Next(image.Width);
            //        int x2 = random.Next(image.Width);
            //        int y1 = random.Next(image.Height);
            //        int y2 = random.Next(image.Height);

            //        g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
            //    }

            //    Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
            //    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            //    g.DrawString(checkCode, font, brush, 2, 2);

            //    //画图片的前景噪音点
            //    for (int i = 0; i < 100; i++)
            //    {
            //        int x = random.Next(image.Width);
            //        int y = random.Next(image.Height);

            //        image.SetPixel(x, y, Color.FromArgb(random.Next()));
            //    }

            //    //画图片的边框线
            //    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            //    image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            //}
            //finally
            //{
            //    g.Dispose();
            //    image.Dispose();
            //}
            //return ms.ToArray();

            #endregion

        }

        /// <summary>
        /// 将BitMap转换为byte[]
        /// </summary>
        /// <param name="checkCode"></param>
        /// <returns></returns>
        protected byte[] BitmapToBytes(Bitmap bitmap)
        {
            MemoryStream ms = new System.IO.MemoryStream();
            bitmap.Save(ms, imageformat);
            return ms.ToArray();
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 验证，并失效成功的验证码 （-1:过期 0：错误 1：成功）
        /// </summary>
        /// <param name="code"></param>
        /// <returns>-1:过期 0：错误 1：成功</returns>
        public virtual int IsValidate(string code, object id)
        {
            var v = GetTempSavedCode(id);
            if (v == null) return -1;
            bool result = string.Compare(Convert.ToString(v), code, true) == 0;
            if (result)
            {
                RemoveTempSaveCode(id);
                return 1;
            }
            else
            {
                return 0;
            }

        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public byte[] CreateImageBytes(object id)
        {
            return BitmapToBytes(CreateImage(id));
        }


        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public Bitmap CreateImage(object id)
        {
            string checkCode = CreateCheckCode();
            SaveTempCode(checkCode, id);
            return CreateBitImage(checkCode);
        }
        /// <summary>
        /// 创建验证数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns>相关的数据</returns>
        public virtual object CreateCode(object id)
        {
            return CreateImageBytes(id);
        }
        #endregion

    }
}
